#include "A_Config.h"

SchoolWiFi schoolWiFi;

bool SchoolWiFi::testConnection()
{
    for (uint8_t i = 0; i < 3; ++i)
    {
        if (client.connect(testHost, testPort))
        {
            client.stop();
            return true;
        }
        delay(500);
    }
    return false;
}
bool SchoolWiFi::connect()
{
    uint8_t tries = 0;
    bool donotsleepstatus = hal.DoNotSleep;
    hal.DoNotSleep = true;
    hal.axpShortPress = false;
    WiFi.mode(WIFI_STA);
    WiFi.begin(SCHOOL_WIFI_SSID, SCHOOL_WIFI_PASSWD);
    while (WiFi.status() != WL_CONNECTED)
    {
        vTaskDelay(500);
        ++tries;
        if (tries > 60 || WiFi.status() == WL_CONNECT_FAILED)
        {
            goto error;
        }
        if (hal.axpShortPress)
        {
            hal.axpShortPress = false;
            goto error;
        }
    }
    hal.DoNotSleep = donotsleepstatus;
    return true;
error:
    WiFi.mode(WIFI_OFF);
    hal.DoNotSleep = donotsleepstatus;
    return false;
}
bool SchoolWiFi::authenticate()
{
    String url = SCHOOL_WIFI_HOST;
    String macAddress;
    url += "?userip=";
    url += WiFi.localIP().toString();
    url += "&usermac=";
    macAddress = WiFi.macAddress();
    macAddress.replace(":", "");
    url += macAddress;
    http.begin(url);
    int httpCode = http.POST(SCHOOL_WIFI_POST_DATA);
    if (httpCode > 0)
    {
        if (httpCode == 302)
        {
            return true;
        }
    }
    return false;
}
